package com.tm.media.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tm.media.login.service.AdUserRoleService;
import com.tm.media.login.service.IAdUserService;
import com.tm.media.model.dtos.ResponseResult;
import com.tm.media.model.entity.AdUser;
import com.tm.media.model.entity.AdUserRoleEntity;
import com.tm.media.model.mapper.AdUserMapper;
import com.tm.media.model.dtos.AdUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 管理员用户信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-02-09
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {
    @Autowired
    private AdUserMapper adUserMapper;
    @Autowired
    private AdUserRoleService adUserRoleService;
    @Override
    public PageUti1l list(PageUti1l pageUti1l) {
       List<AdUserDto> list= adUserMapper.list(pageUti1l);
        Long count = Long.parseLong(adUserMapper.selectCount(null).toString());
        pageUti1l.setTotalCount(count);
        pageUti1l.setData(list);
        return pageUti1l;
    }

    @Override
    public ResponseResult addUser(AdUser adUser) {
        if (adUser.getId()!=null){
            baseMapper.updateById(adUser);
        }else {
            QueryWrapper<AdUser> wrapper = new QueryWrapper<>();
            wrapper.eq("name",adUser.getName());
            Integer count = baseMapper.selectCount(wrapper);
            if (count<1){
                adUser.setCreatedTime(LocalDateTime.now());
                adUser.setLoginTime(LocalDateTime.now());
                baseMapper.insert(adUser);
                //用户新增角色表
                AdUserRoleEntity adUserRoleEntity = new AdUserRoleEntity();
                adUserRoleEntity.setUserId(adUser.getId());
                adUserRoleEntity.setRoleId(adUser.getAdRoleId());
                adUserRoleEntity.setCreatedTime(LocalDateTime.now());
                adUserRoleService.save(adUserRoleEntity);
                return ResponseResult.okResult(200,"新增成功");
            }
        }
      return   ResponseResult.okResult(500,"用户名重复");
    }

    @Override
    public ResponseResult deleteUserById(Integer id) {
        baseMapper.deleteById(id);
        return ResponseResult.okResult(200);
    }
}
